package com.guxingke.gblog.controller.back;

import java.io.File;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.guxingke.gblog.controller.BaseController;
import com.guxingke.gblog.util.PictureUtil;
import com.guxingke.gblog.util.PropertiesUtil;

@Controller
@RequestMapping("/manage/picture")
public class PictureManageController extends BaseController {

	@RequestMapping
	public ModelAndView list(HttpSession session) {
		ModelAndView mav = new ModelAndView();

		mav.addObject("mainPage", "picture/detail.jsp");

		mav.setViewName("manage");
		return mav;
	}

	@RequestMapping("/upload")
	public String uploadFile(
			@RequestParam("userImage") MultipartFile userImage,
			@RequestParam("articleImage") MultipartFile articleImage,
			HttpSession session) throws Exception {
		String imageBasePath = session.getServletContext().getRealPath("image");

		if (!userImage.isEmpty()) {
			String userImagePath = imageBasePath + File.separator
					+ PropertiesUtil.getValue("userPicturePath")
					+ File.separator + userImage.getOriginalFilename();

			System.out.println(userImagePath);

			userImage.transferTo(new File(userImagePath));
			// 更新session 缓存
			session.setAttribute(
					"userImages",
					PictureUtil.getPictures(imageBasePath,
							PropertiesUtil.getValue("userPicturePath")));
		}

		if (!articleImage.isEmpty()) {
			String articleImagePath = imageBasePath + File.separator
					+ PropertiesUtil.getValue("articlePicturePath")
					+ File.separator + articleImage.getOriginalFilename();

			System.out.println(articleImagePath);

			articleImage.transferTo(new File(articleImagePath));

			// 更新session 缓存
			session.setAttribute(
					"articleImages",
					PictureUtil.getPictures(imageBasePath,
							PropertiesUtil.getValue("articlePicturePath")));
		}

		return "redirect:/manage/picture.do";
	}
}
